package org.cx.comparator;

import lombok.RequiredArgsConstructor;

import java.util.IdentityHashMap;
import java.util.Map;


@RequiredArgsConstructor
public class ComparatorRegistry {

    private final Map<Class<?>, ComparatorProxyFactory> knownComparators = new IdentityHashMap<>();
    private final ComparatorConfiguration configuration;


    public <T> T getComparator(Class<T> type) {
        final ComparatorProxyFactory<T> comparatorProxyFactory = knownComparators.get(type);
        if (comparatorProxyFactory == null) {
            throw new ComparatorException("Type " + type + " is not known to the ComparatorRegistry.");
        }
        return comparatorProxyFactory.newInstance();
    }

    public <T> boolean hasComparator(Class<T> type) {
        return knownComparators.containsKey(type);
    }

    public <T> void addComparator(Class<T> type) {
        if (type.isInterface()) {
            if (hasComparator(type)) {
                throw new ComparatorException("Type " + type + " is already known to the ComparatorRegistry.");
            }
        }
        knownComparators.put(type, new ComparatorProxyFactory(type, configuration));
    }
}
